<template>
  <GlobalDrawer
    v-model="visible"
    :title="formTitle"
    size="80%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <!-- 公共字段 -->
      <el-form-item label="客户" prop="customer_id">
        <el-select
          v-model="form.customer_id"
          placeholder="请选择客户"
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="item in customerOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入订单标题" />
      </el-form-item>

      <el-form-item label="订单金额" prop="amount">
        <el-input-number v-model="form.amount" :min="0" :precision="2" style="width: 100%" />
      </el-form-item>

      <el-form-item label="付款方式" prop="payment_type">
        <el-select v-model="form.payment_type" placeholder="请选择付款方式" style="width: 100%">
          <el-option
            v-for="item in paymentMethodOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 订单类别选择 -->
      <el-form-item label="订单类别" prop="order_category">
        <el-radio-group v-model="form.order_category">
          <el-radio :label="2">诉讼订单</el-radio>
          <el-radio :label="3">法务订单</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 诉讼订单特有字段 -->
      <template v-if="form.order_category === 2">
        <el-divider content-position="left">诉讼订单信息</el-divider>

        <el-form-item label="首单体验" prop="is_first_order">
          <el-radio-group v-model="form.is_first_order">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="下单类型" prop="order_type">
          <el-radio-group v-model="form.order_type">
            <el-radio :label="1">案件代理</el-radio>
            <el-radio :label="2">诉讼指导</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="委托方" prop="entrusting_party_type">
          <el-radio-group v-model="form.entrusting_party_type">
            <el-radio :label="1">原告</el-radio>
            <el-radio :label="2">被告</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="委托方名称" prop="entrusting_party_name">
          <el-input v-model="form.entrusting_party_name" placeholder="请输入委托方名称" />
        </el-form-item>

        <el-form-item label="相对方" prop="opposing_party_type">
          <el-radio-group v-model="form.opposing_party_type">
            <el-radio :label="1">原告</el-radio>
            <el-radio :label="2">被告</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="相对方名称" prop="opposing_party_name">
          <el-input v-model="form.opposing_party_name" placeholder="请输入相对方名称" />
        </el-form-item>

        <el-form-item label="联系人" prop="contact_person">
          <el-input v-model="form.contact_person" placeholder="请输入联系人" />
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="form.contact_phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="前期费用" prop="service_fee_pre">
          <el-input-number
            v-model="form.service_fee_pre"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="后期费用">
          <el-input-number
            v-model="form.service_fee_post"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
          <div class="el-form-item__help">回款后付</div>
        </el-form-item>

        <el-form-item label="案由" prop="case_type">
          <el-checkbox-group v-model="form.case_type">
            <el-checkbox :label="1">合同</el-checkbox>
            <el-checkbox :label="2">股权</el-checkbox>
            <el-checkbox :label="3">劳动</el-checkbox>
            <el-checkbox :label="4">金融</el-checkbox>
            <el-checkbox :label="5">借贷</el-checkbox>
            <el-checkbox :label="6">工伤</el-checkbox>
            <el-checkbox :label="7">婚姻</el-checkbox>
            <el-checkbox :label="8">刑事</el-checkbox>
            <el-checkbox :label="9">破产</el-checkbox>
            <el-checkbox :label="10">其他</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item v-if="form.case_type.includes(10)" label="其他案由">
          <el-input v-model="form.case_type_other" placeholder="请输入其他案由" />
        </el-form-item>

        <el-form-item label="民商阶段">
          <el-checkbox-group v-model="form.civil_phase">
            <el-checkbox label="仲裁">仲裁</el-checkbox>
            <el-checkbox label="一审">一审</el-checkbox>
            <el-checkbox label="二审">二审</el-checkbox>
            <el-checkbox label="再审">再审</el-checkbox>
            <el-checkbox label="执行">执行</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="刑事阶段">
          <el-checkbox-group v-model="form.criminal_phase">
            <el-checkbox label="会见">会见</el-checkbox>
            <el-checkbox label="上诉">上诉</el-checkbox>
            <el-checkbox label="公安">公安</el-checkbox>
            <el-checkbox label="检察院">检察院</el-checkbox>
            <el-checkbox label="法院">法院</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="标的金额" prop="case_amount_range">
          <el-radio-group v-model="form.case_amount_range">
            <el-radio :label="1">5万以下</el-radio>
            <el-radio :label="2">5-10万</el-radio>
            <el-radio :label="3">10-50万</el-radio>
            <el-radio :label="4">50-100万</el-radio>
            <el-radio :label="5">100万以上</el-radio>
            <el-radio :label="6">其他</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.case_amount_range === 6" label="其他金额">
          <el-input v-model="form.case_amount_other" placeholder="请输入其他金额" />
        </el-form-item>

        <el-form-item label="诉讼请求要素">
          <el-checkbox-group v-model="form.lawsuit_request_elements">
            <el-checkbox label="违约金">违约金</el-checkbox>
            <el-checkbox label="利息">利息</el-checkbox>
            <el-checkbox label="诉讼费">诉讼费</el-checkbox>
            <el-checkbox label="律师费">律师费</el-checkbox>
            <el-checkbox label="保全费">保全费</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="主要诉讼请求">
          <el-input
            v-model="form.main_lawsuit_request"
            type="textarea"
            :rows="4"
            placeholder="请输入主要诉讼请求"
          />
        </el-form-item>
      </template>

      <!-- 法务订单特有字段 -->
      <template v-if="form.order_category === 3">
        <el-divider content-position="left">法务订单信息</el-divider>

        <el-form-item label="客户名称" prop="customer_name">
          <el-input v-model="form.customer_name" placeholder="请输入客户名称" />
        </el-form-item>

        <el-form-item label="联系人" prop="contact_person">
          <el-input v-model="form.contact_person" placeholder="请输入联系人" />
        </el-form-item>

        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="form.contact_phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="套餐类型" prop="package_type">
          <el-radio-group v-model="form.package_type">
            <el-radio :label="1">普通版</el-radio>
            <el-radio :label="2">标准版</el-radio>
            <el-radio :label="3">VIP版</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="账号类型" prop="account_type">
          <el-radio-group v-model="form.account_type">
            <el-radio :label="1">主账号</el-radio>
            <el-radio :label="2">子账号</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.account_type === 2" label="归属合同主体">
          <el-input v-model="form.sub_account_owner" placeholder="请输入子账号归属合同主体" />
        </el-form-item>

        <el-form-item label="首单体验服务">
          <el-radio-group v-model="form.is_first_order_service">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="诉讼指导数量">
          <el-input-number v-model="form.lawsuit_guidance_count" :min="0" style="width: 100%" />
          <div class="el-form-item__help">单位：件</div>
        </el-form-item>

        <el-form-item label="商账追款数量">
          <el-input-number v-model="form.debt_collection_count" :min="0" style="width: 100%" />
          <div class="el-form-item__help">单位：家</div>
        </el-form-item>

        <el-form-item label="法律函件数量">
          <el-input-number v-model="form.legal_letter_count" :min="0" style="width: 100%" />
          <div class="el-form-item__help">单位：份</div>
        </el-form-item>

        <el-form-item label="合同起草数量">
          <el-input-number v-model="form.contract_draft_count" :min="0" style="width: 100%" />
          <div class="el-form-item__help">单位：份</div>
        </el-form-item>

        <el-form-item label="合同审查数量">
          <el-input-number v-model="form.contract_review_count" :min="0" style="width: 100%" />
          <div class="el-form-item__help">单位：份</div>
        </el-form-item>

        <el-form-item label="专项服务类型">
          <el-checkbox-group v-model="form.special_service_types">
            <el-checkbox label="人资合规">人资合规</el-checkbox>
            <el-checkbox label="股权架构">股权架构</el-checkbox>
            <el-checkbox label="股权激励">股权激励</el-checkbox>
            <el-checkbox label="投融资">投融资</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </template>

      <!-- 审批相关字段 -->
      <el-divider content-position="left">审批信息</el-divider>

      <el-form-item label="商务经理">
        <el-input v-model="form.business_manager" placeholder="请输入商务经理姓名" />
      </el-form-item>

      <el-form-item label="部门主管">
        <el-input v-model="form.department_manager" placeholder="请输入部门主管姓名" />
      </el-form-item>

      <el-form-item label="合同管理部">
        <el-input v-model="form.contract_manager" placeholder="请输入合同管理部负责人" />
      </el-form-item>

      <el-form-item label="财务管理部">
        <el-input v-model="form.finance_manager" placeholder="请输入财务管理部负责人" />
      </el-form-item>

      <el-form-item label="诉讼管理部">
        <el-input v-model="form.lawsuit_manager" placeholder="请输入诉讼管理部负责人" />
      </el-form-item>

      <el-form-item label="主办律师">
        <el-input v-model="form.lead_lawyer" placeholder="请输入主办律师姓名" />
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { orderApi, customerApi } from '@/api/crm'
  import { lawsuitLegalOrderApi } from '@/api/crm/lawsuitLegalOrderApi'
  import type { Order } from '@/types/crm'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: Number,
      default: 0,
    },
    customerId: {
      type: Number,
      default: 0,
    },
    orderType: {
      type: String,
      default: 'lawsuit', // 'lawsuit' 或 'legal'
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const formRef = ref()
  const loading = ref(false)
  const submitting = ref(false)

  // 表单数据
  const form = reactive({
    // 基础订单字段
    customer_id: 0,
    order_type: 1,
    order_category: 2, // 默认诉讼订单，但会根据orderType属性自动调整
    title: '',
    amount: 0,
    payment_type: 1,
    // 诉讼订单字段

    is_first_order: 0,
    entrusting_party_type: 1,
    entrusting_party_name: '',
    opposing_party_type: 2,
    opposing_party_name: '',
    contact_person: '',
    contact_phone: '',
    service_fee_pre: 0,
    service_fee_post: 0,
    case_type: [] as number[],
    case_type_other: '',
    civil_phase: [] as string[],
    criminal_phase: [] as string[],
    case_amount_range: 1,
    case_amount_other: '',
    lawsuit_request_elements: [] as string[],
    main_lawsuit_request: '',
    // 法务订单字段
    customer_name: '',
    package_type: 1,
    account_type: 1,
    sub_account_owner: '',
    is_first_order_service: 0,
    lawsuit_guidance_count: 0,
    debt_collection_count: 0,
    legal_letter_count: 0,
    contract_draft_count: 0,
    contract_review_count: 0,
    special_service_types: [] as string[],
    // 审批字段
    business_manager: '',
    department_manager: '',
    contract_manager: '',
    finance_manager: '',
    lawsuit_manager: '',
    lead_lawyer: '',
  })

  // 表单验证规则
  const rules = {
    customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
    title: [{ required: true, message: '请输入订单标题', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
    payment_type: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
    // 诉讼订单验证规则
    entrusting_party_type: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 2 && value === undefined) {
            callback(new Error('请选择委托方类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    entrusting_party_name: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 2 && !value) {
            callback(new Error('请输入委托方名称'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
    opposing_party_type: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 2 && value === undefined) {
            callback(new Error('请选择相对方类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    opposing_party_name: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 2 && !value) {
            callback(new Error('请输入相对方名称'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
    contact_person: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
    service_fee_pre: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 2 && value === undefined) {
            callback(new Error('请输入前期费用'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
    case_type: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 2 && (!value || value.length === 0)) {
            callback(new Error('请选择案由'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    case_amount_range: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 2 && value === undefined) {
            callback(new Error('请选择标的金额范围'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    // 法务订单验证规则
    customer_name: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 3 && !value) {
            callback(new Error('请输入客户名称'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
    contact_phone: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 3 && !value) {
            callback(new Error('请输入联系电话'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
    package_type: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 3 && value === undefined) {
            callback(new Error('请选择套餐类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
    account_type: [
      {
        required: (rule: any, value: any, callback: any) => {
          if (form.order_category === 3 && value === undefined) {
            callback(new Error('请选择账号类型'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
  }

  const customerOptions = ref<Array<{ id: number; name: string }>>([])
  const paymentMethodOptions = ref<Array<{ value: string; label: string }>>([])

  // 表单标题
  const formTitle = computed(() => {
    if (props.orderId) {
      return '编辑特殊订单'
    }
    if (form.order_category === 2) {
      return '新增诉讼订单'
    }
    return '新增法务订单'
  })

  // 初始化表单数据
  const initForm = () => {
    // 设置客户ID
    if (props.customerId) {
      form.customer_id = props.customerId
    }

    // 根据orderType设置订单类别
    if (props.orderType === 'legal') {
      form.order_category = 3 // 法务订单
    } else {
      form.order_category = 2 // 默认诉讼订单
    }
  }

  // 获取选项数据
  const getOptions = async () => {
    try {
      const [customerRes, paymentMethodRes] = await Promise.all([
        customerApi.getCustomerOptions(),
        orderApi.getPaymentMethodOptions(),
      ])
      customerOptions.value = customerRes.data.map(
        (item: { value: string | number; label: string }) => ({
          id: item.value,
          name: item.label,
        })
      )
      paymentMethodOptions.value = paymentMethodRes.data
    } catch (error) {
      console.error('获取选项失败:', error)
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    submitting.value = true

    try {
      await formRef.value.validate()

      // 构建基础订单数据
      const baseOrderData = {
        customer_id: form.customer_id,
        order_type: form.order_type,
        order_category: form.order_category,
        title: form.title,
        amount: form.amount,
        payment_type: form.payment_type,
        status: 1,
        payment_status: 1,
        contract_status: 1,
        user_id: 1,
      }

      let orderId: number

      if (props.orderId) {
        // 更新现有订单
        await orderApi.update({ ...baseOrderData, id: props.orderId })
        orderId = props.orderId
        ElMessage.success('编辑成功')
      } else {
        // 创建新订单
        const res = await orderApi.create(baseOrderData)
        orderId = res.data.id
        ElMessage.success('新增成功')
      }

      // 根据订单类别，构建特定订单数据并保存
      if (form.order_category === 2) {
        // 诉讼订单数据
        const lawsuitOrderData = {
          order_id: orderId,
          customer_id: form.customer_id,

          is_first_order: form.is_first_order,
          order_type: form.order_type,
          entrusting_party_type: form.entrusting_party_type,
          entrusting_party_name: form.entrusting_party_name,
          opposing_party_type: form.opposing_party_type,
          opposing_party_name: form.opposing_party_name,
          contact_person: form.contact_person,
          contact_phone: form.contact_phone,
          service_fee_pre: form.service_fee_pre,
          service_fee_post: form.service_fee_post,
          case_type: form.case_type.join(','), // 存储为逗号分隔的字符串
          case_type_other: form.case_type_other,
          civil_phase: form.civil_phase.join(','),
          criminal_phase: form.criminal_phase.join(','),
          case_amount_range: form.case_amount_range,
          case_amount_other: form.case_amount_other,
          lawsuit_request_elements: form.lawsuit_request_elements.join(','),
          main_lawsuit_request: form.main_lawsuit_request,
          business_manager: form.business_manager,
          department_manager: form.department_manager,
          contract_manager: form.contract_manager,
          finance_manager: form.finance_manager,
          lawsuit_manager: form.lawsuit_manager,
          lead_lawyer: form.lead_lawyer,
        }

        // 调用专门的API来保存诉讼订单数据
        await lawsuitLegalOrderApi.saveLawsuitOrder({
          ...lawsuitOrderData,

          is_first_order: lawsuitOrderData.is_first_order as 0 | 1,
          order_type: lawsuitOrderData.order_type as 1 | 2,
          entrusting_party_type: lawsuitOrderData.entrusting_party_type as 1 | 2,
          opposing_party_type: lawsuitOrderData.opposing_party_type as 1 | 2,
          case_type: Array.isArray(lawsuitOrderData.case_type)
            ? lawsuitOrderData.case_type.map(Number)
            : [Number(lawsuitOrderData.case_type)],
          civil_phase: Array.isArray(lawsuitOrderData.civil_phase)
            ? lawsuitOrderData.civil_phase
            : [String(lawsuitOrderData.civil_phase)],
          criminal_phase: Array.isArray(lawsuitOrderData.criminal_phase)
            ? lawsuitOrderData.criminal_phase
            : [String(lawsuitOrderData.criminal_phase)],
          lawsuit_request_elements: Array.isArray(lawsuitOrderData.lawsuit_request_elements)
            ? lawsuitOrderData.lawsuit_request_elements
            : [String(lawsuitOrderData.lawsuit_request_elements)],
        })
      } else if (form.order_category === 3) {
        // 法务订单数据
        const legalOrderData = {
          order_id: orderId,
          customer_id: form.customer_id,
          customer_name: form.customer_name,
          contact_person: form.contact_person,
          contact_phone: form.contact_phone,
          service_fee: form.amount,
          package_type: form.package_type,
          account_type: form.account_type,
          sub_account_owner: form.sub_account_owner,
          is_first_order_service: form.is_first_order_service,
          lawsuit_guidance_count: form.lawsuit_guidance_count,
          debt_collection_count: form.debt_collection_count,
          legal_letter_count: form.legal_letter_count,
          contract_draft_count: form.contract_draft_count,
          contract_review_count: form.contract_review_count,
          special_service_types: form.special_service_types.join(','),

          business_manager: form.business_manager,
          department_manager: form.department_manager,
          contract_manager: form.contract_manager,
          finance_manager: form.finance_manager,
          lawsuit_manager: form.lawsuit_manager,
          lead_lawyer: form.lead_lawyer,
        }

        // 调用专门的API来保存法务订单数据
        await lawsuitLegalOrderApi.saveLegalOrder({
          ...legalOrderData,

          is_first_order_service: legalOrderData.is_first_order_service as 0 | 1,
          package_type: legalOrderData.package_type as 1 | 2 | 3,
          account_type: legalOrderData.account_type as 1 | 2,
          special_service_types: Array.isArray(legalOrderData.special_service_types)
            ? legalOrderData.special_service_types
            : [String(legalOrderData.special_service_types)],
        })
      }

      emit('success')
      handleClose()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitting.value = false
    }
  }

  // 关闭对话框
  const handleClose = () => {
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields()
    }

    // 重置所有字段
    Object.keys(form).forEach(key => {
      if (key !== 'order_category') {
        if (Array.isArray((form as any)[key])) {
          ;(form as any)[key] = []
        } else {
          ;(form as any)[key] = ''
        }
      }
    })

    // 重置数字字段
    form.customer_id = 0
    form.order_type = 1
    form.amount = 0
    form.payment_type = 1

    form.is_first_order = 0
    form.entrusting_party_type = 1
    form.opposing_party_type = 2
    form.service_fee_pre = 0
    form.service_fee_post = 0
    form.case_amount_range = 1
    form.package_type = 1
    form.account_type = 1
    form.is_first_order_service = 0
    form.lawsuit_guidance_count = 0
    form.debt_collection_count = 0
    form.legal_letter_count = 0
    form.contract_draft_count = 0
    form.contract_review_count = 0

    visible.value = false
  }

  // 监听对话框显示状态
  watch(visible, newVal => {
    if (newVal) {
      getOptions()
      initForm()
    }
  })
</script>

<style scoped>
  .el-form {
    padding-right: 20px;
  }

  .el-form-item__help {
    margin-top: 4px;
    color: #909399;
    font-size: 12px;
  }
</style>
